/*
 * Created on 2005-10-7
 * Last modified on 2007-6-6
 * Powered by YeQiangWei.com
 */
package com.yeqiangwei.util;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
/**
 * 
 * @author YeQiangWei by 我容易么我
 * Powered by YeQiangWei.com
 */
public class ParamUtils {
	
	private static final Logger logger = Logger.getLogger(ParamUtils.class);
	
	public static String getStringAttribute(HttpServletRequest request
			,String name, String str)
	{
		if(Validator.isEmpty(request)){
			return str;
		}
		if(request.getAttribute(name)==null){
			return str;
		}else{
			return String.valueOf(request.getAttribute(name));
		}
	}
	
	public static int getIntAttribute(HttpServletRequest request
			,String name, int i)
	{
		if(Validator.isEmpty(request)){
			return i;
		}
		if(request.getAttribute(name)==null){
			return i;
		}
		String str = String.valueOf(request.getAttribute(name));
		if(Utils.isNumber(str)){
			return TypeChange.stringToInt(str);
		}else{
			return i;
		}
	}
	
	public static Object getAttribute(HttpServletRequest request
			,String name)
	{
		if(Validator.isEmpty(request)){
			return null;
		}
		return request.getAttribute(name);
	}
	
	public static String getRealPath(ServletConfig config){ 
		return getRealPath(config.getServletContext());
	}
	
	public static String getRealPath(HttpSession session){ 
		return getRealPath(session.getServletContext());
	}
	
	public static String getRealPath(HttpServletRequest request){
		if(request==null){
			return null;
		}else{
			return getRealPath(request.getSession());
		}
	}
	
	public static String getRealPath(ServletContext context){
		return context.getRealPath("/");
	}
	
	public static String getHashMapString(HashMap hm, String get){
		if(hm==null){
            return "";
        }else{
            return hm.get(get).toString();
        }
	}
	
	public static int getHashMapInt(HashMap hm, String get){
		if(hm==null){
            return 0;
        }else{
            return TypeChange.objToInt(hm.get(get));
        }
	}
	
	public static double getHashMapDouble(HashMap hm, String get){
		if(hm==null){
            return 0;
        }else{
            return TypeChange.objToDouble(hm.get(get));
        }
	}
	
	public static short getHashMapShort(HashMap hm, String get){
		if(hm==null){
            return 0;
        }else{
            return TypeChange.objToShort(hm.get(get));
        }
	}
	
	public static String getSessionString(HttpServletRequest req
			, String name, String val)
	{
		String value = val;
		HttpSession httpsession = req.getSession(true);
		if(httpsession!=null){
			if(httpsession.getAttribute(name)!=null){
				value = String.valueOf(httpsession.getAttribute(name)).trim();
			}
		}
		return value;
	}
	
	public static int getSessionInt(HttpServletRequest req
			, String name, int val)
	{
		String 	value = ParamUtils.getSessionString(req,name,String.valueOf(val));
		int i = TypeChange.stringToInt(value);
		return i;
	}
	
	public static boolean getSessionBoolean(HttpServletRequest req
			, String name, boolean val)
	{
		boolean value = val;
		HttpSession httpsession = req.getSession(true);
		if(httpsession!=null){
			if(httpsession.getAttribute(name)!=null){
				value = TypeChange.objToBoolean(httpsession.getAttribute(name));
			}
		}
		return value;
	}
	
	
	public static void setSession(HttpServletRequest req
			, String name, Object obj)
	{
		HttpSession httpsession = req.getSession(true);
		httpsession.setAttribute(name, obj);
	}
	
	@SuppressWarnings("unchecked")
	public static <Obj> Obj getSessionObject(HttpServletRequest req
			, String name, Obj val){
		HttpSession httpsession = req.getSession(true);
		Obj obj = val;
		if(httpsession!=null){
			if(httpsession.getAttribute(name)!=null){
				obj = (Obj) httpsession.getAttribute(name);
			}
		}
		return obj;
	}
	
	/***
	 * 获取cookie 转化为 Int 默认值为0
	 * Made in 2007-9-10上午01:16:54
	 *  
	 *@param req
	 *@param name
	 *@return
	 *
	 */
	public static int getIntCookieValue(HttpServletRequest req	, String name){
		return TypeChange.stringToInt(getCookieValue(req,name,"0"));
	}
	/**
	 * 获取cookies value值
	 * @param req
	 * @param Name
	 * @param val cookies为NULL返回默认值
	 * @return
	 * 2005-12-30 14:15:37 Made In YeQiangWei
	 * com.yeqiangwei.util
	 */
	public static String getCookieValue(HttpServletRequest req
			, String name, String val)
	{
		if(Validator.isEmpty(req)){
			return val;
		}
		String value = val;
		Cookie[] cookies = req.getCookies();
		if (cookies==null||cookies.length==0){
			return val;
		}
		for (int i = 0; i < cookies.length; i++)
		{
			Cookie c = cookies[i];
			if(name.equals(c.getName())){
				value = c.getValue().trim();
				value = com.yeqiangwei.net.URL.urlDecoder(value,"UTF-8");
			}	
		}
		return value;
	}
	
	public static void setCookieValue(HttpServletResponse rep, String name, String value, int day)
	{
		if(Validator.isEmpty(rep)){
			return ;
		}
		value = com.yeqiangwei.net.URL.urlEncoder(value,"UTF-8");
		Cookie cookie = new Cookie(name, value);
		if(day>0){
			cookie.setMaxAge(day*60*60*24);
		}
		rep.addCookie(cookie);
	}
	
	public static void setCookieValue(HttpServletResponse rep, String domain
			, String name, int value, int day)
	{
		setCookieValue(rep,domain,name,String.valueOf(value),day);
	}
	
	public static void setCookieValue(HttpServletResponse rep, String domain
			, String name, String value, int day)
	{
		if(Validator.isEmpty(rep)){
			return ;
		}
		value = com.yeqiangwei.net.URL.urlEncoder(value,"UTF-8");
		Cookie cookie = new Cookie(name, value);
		cookie.setDomain(domain);
		cookie.setPath("/");
		if(day>0){
			cookie.setMaxAge(day*60*60*24);
		}
		rep.addCookie(cookie);
	}
	
    public static String getStringParameter(HttpServletRequest request,
            String name)
    {
        return getStringParameter(request,name,"");
    }
    
    /**
     * 指定默认值
     * @param request
     * @param name 如果request.getParameter(name)为null 则返回snull
     * @param snull 
     * @return
     * 2005-11-18 12:36:37 Made In YeQiangWei
     * com.yeqiangwei.util
     */
    public static String getStringParameter(HttpServletRequest request,
            String name, String defaultStr)
    {
        if(!Validator.isEmpty(request)&&!Validator.isEmpty(request.getParameter(name))){
        	return TypeChange.nullOfString(request.getParameter(name).trim());
        }else{
        	return defaultStr;
        }
    }
    

    public static String getRequestURI(HttpServletRequest request, String defaultStr)
    {
        if(!Validator.isEmpty(request)){
        	return request.getRequestURI();
        }else{
        	return defaultStr;
        }
    }
    
    public static String getStringAuto(HttpServletRequest request, String name, String defaultStr)
    {
    	if(Validator.isEmpty(request)){
    		logger.debug("request is null");
    		return defaultStr;
    	}
    	String i;
    	if(Validator.isEmpty(request.getAttribute(name))){
    		i = request.getParameter(name);
    	}else{
    		i = String.valueOf(request.getAttribute(name));
    	}
    	if(Validator.isEmpty(i)){
    		i = defaultStr;
    	}
        return i;
    }
    
    public static int getIntAuto(HttpServletRequest request, String name)
    {
        return TypeChange.stringToInt(getStringAuto(request,name,"0"));
    }
    /**
     * 默认值为0
     * @param request
     * @param name
     * @return
     * 2005-11-18 11:43:35 Made In YeQiangWei
     * com.yeqiangwei.util
     */
    public static int getIntParameter(HttpServletRequest request, String name)
    {
        return getIntParameter(request,name,0);
    }
    
    /**
     * 指定默认值
     * @param request
     * @param name
     * @param inull 如果request.getParameter(name)为null 则返回inull
     * @return
     * 2005-11-18 11:43:58 Made In YeQiangWei
     * com.yeqiangwei.util
     */
    public static int getIntParameter(HttpServletRequest request,
            String name, int defaultInt)
    {
        int i = defaultInt;
        if(!Validator.isEmpty(request)){
        	i = TypeChange.stringToInt(request.getParameter(name),defaultInt);
        }
        return i ;
    }
    
    public static double getDoubleParameter(HttpServletRequest request,
            String name, double isnull)
    {
        double d = 0;
        if(!Validator.isEmpty(request)){
        	d = TypeChange.stringToDouble(request.getParameter(name));
        }
        return d;
    }
    
    public static double getDoubleParameter(HttpServletRequest request,
            String name)
    {
        double d = TypeChange.stringToDouble(request.getParameter(name));
        return d;
    }
    
    public static boolean getBooleanParameter(HttpServletRequest request,
            String name)
    {
        boolean b = TypeChange.stringToBoolean(request.getParameter(name));
        return b;
    }
    
    public static boolean getBooleanParameter(HttpServletRequest request,
            String name, boolean b)
    {
    	boolean bea;
    	if(request.getParameter(name)==null){
    		bea = b;
    	}else{
    		bea = TypeChange.stringToBoolean(request.getParameter(name));
    	}
        return bea;
    }
    
    public static long getLongParameter(HttpServletRequest request,
            String name)
    {
        return TypeChange.stringToLong(request.getParameter(name));
    }  
    
    
    /**
     * 无默认值
     * @param request
     * @param name
     * @return
     * 2005-11-18 11:45:30 Made In YeQiangWei
     * com.yeqiangwei.util
     */
    public static byte getByteParameter(HttpServletRequest request,
            String name)
    {
        byte b = TypeChange.stringToByte(request.getParameter(name));
        return b;
    }  
    
    /**
     * 指定默认值 
     * @param request
     * @param name
     * @param bnull  如果request.getParameter(name)为null 则返回bnull
     * @return
     * 2005-11-18 11:46:00 Made In YeQiangWei
     * com.yeqiangwei.util
     */
    public static byte getByteParameter(HttpServletRequest request,
            String name, byte bnull)
    {
        if(request.getParameter(name)!=null
        		&& !request.getParameter(name).equals("")){
        	return TypeChange.stringToByte(request.getParameter(name));
        }else{
        	return bnull;
        }
    } 
    
    
    /**
     * 默认值为0
     * @param request
     * @param name
     * @return
     * 2005-11-18 11:48:35 Made In YeQiangWei
     * com.yeqiangwei.util
     */
    public static short getShortParameter(HttpServletRequest request,
            String name)
    {
        return TypeChange.stringToShort(request.getParameter(name));
    } 
    
    /**
     * 指定默认值 如果request.getParameter(name)为null 则返回snull
     * @param request
     * @param name 
     * @param snull
     * @return
     * 2005-11-18 11:49:02 Made In YeQiangWei
     * com.yeqiangwei.util
     */
    public static short getShortParameter(HttpServletRequest request,
            String name, short snull)
    {
        short s = snull;
        if(request.getParameter(name)!=null
        		&& !request.getParameter(name).equals(""))
        	s = TypeChange.stringToShort(request.getParameter(name));
        return s;
    }
/**
 * 
 * com.yeqiangwei.util
 * made by XuFeng
 *  2007-7-18 下午07:52:05 
 * @param request
 * @param name
 * @return
 */
    
    public static String getStringParameterFromGet(HttpServletRequest request, String name)
    {
        String value=request.getParameter(name);
        if("GET".compareToIgnoreCase(request.getMethod())==0 && value!=null)
        {
            try {
                value=new String(value.getBytes("iso8859-1"),"utf-8");
            } catch (UnsupportedEncodingException e)
            {
                logger.error(e.toString());
            }
        }
        return value==null?"":value.trim();
    }
public static String getUserExploer(HttpServletRequest request){
		String user=request.getHeader("user-agent");
		String userExploer="其他类型的浏览器";
		if(user.indexOf("MSIE 6.0")>0)userExploer="IE 6.0";
		if(user.indexOf("MSIE 7.0")>0)userExploer="IE 7.0";
		if(user.indexOf("Firefox")>0)userExploer="Firefox";
		if(user.indexOf("SeaMonkey")>0)userExploer="SeaMonkey";
		if(user.indexOf("Safari")>0)userExploer="Safari";
		if(user.indexOf("MAXTHON ")>0)userExploer="Maxthon 遨游 ";
		return userExploer;
		
}
public static String getUserExploer(String str){
	//String user=request.getHeader("user-agent");
	String userExploer="其他类型的浏览器";
	if(str.indexOf("MSIE 6.0")>0)userExploer="IE 6.0";
	if(str.indexOf("MSIE 7.0")>0)userExploer="IE 7.0";
	if(str.indexOf("Firefox")>0)userExploer="Firefox";
	if(str.indexOf("MAXTHON ")>0)userExploer="Maxthon 遨游 ";
	return userExploer;
	
}
/***
 * 生成的格式为 (5,6,4,3,1)
 * Made in 2007-11-8上午08:12:39
 *  
 *@param request
 *@param name
 *@return
 *
 */
public static String getStringParamValuesWith(HttpServletRequest request, String name){
	String values[]=request.getParameterValues(name);
	StringBuffer sb=new StringBuffer(); 
	sb.append("(");
	if(values!=null&&values.length>0){
		for(int i=0;i<values.length;i++){
		if(i==values.length-1)sb.append(values[i]);
		else sb.append(values[i]+",");
	}
		sb.append(")");
	}
	return sb.toString();
}
 /***
  * 生成的格式为  5,6,4,3,1  
  * Made in 2007-12-1上午06:59:40
  *  
  *@param request
  *@param name
  *@return
  *
  */

public static String getStringParamValuesWithout(HttpServletRequest request, String name){
	String values[]=request.getParameterValues(name);
	StringBuffer sb=new StringBuffer(); 
	if(values!=null&&values.length>0){
		for(int i=0;i<values.length;i++){
		if(i==values.length-1)sb.append(values[i]);
		else sb.append(values[i]+",");
	}		 
	}
	return sb.toString();
}

public static void main(String[] args) {
	//System.out.print(getUserExploer("Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727) "));
	StringBuffer sb=new StringBuffer(); 
	System.out.print(sb.toString());
}
    
}
